package com.glebusheg
{
	import com.bubbler.farm.data.GameFeature;
	import com.bubbler.farm.data.LocalSave;
	import com.bubbler.farm.social.NetworkEvent;
	import com.bubbler.farm.social.NetworkManager;
	import com.bubbler.farm.social.NetworkType;
	import com.bubbler.farm.social.RunMode;
	import org.trexarms.Console;
	
	import com.ek.asset.AssetLoader;
	import com.ek.asset.AssetManager;
	import com.ek.text.StringManager;
	import com.ek.ui.UIProgressBar;
	import com.ek.ui.UIText;
	import com.ek.utils.VisualUtil;

	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.system.Security;

	/**
	 * @author eliasku
	 */
	public class AppLoader extends Sprite
	{
		private static const CONSOLE_TITLE:String = "HOF";	
		
		private static const ASSETS:Object = 
		{
			"asset":"asset.xml"
		};
		
		private var _descriptionLoader:AssetLoader;
        private var _descriptionLoaded:Boolean;
		
		private var _assetLoader:AssetLoader;
        private var _assetLoaded:Boolean;
        private var _networkReady:Boolean;
        private var _someError:Boolean;
        
		private var _preloader:Sprite;
		private var _progressBar:UIProgressBar;
		
		private var _main:AppMain;
		
		public function AppLoader(main:AppMain)
		{
			super();
			
			_main = main;
			
			if(!stage)
				addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			else
				onAddedToStage(null);
		}
		
		private function onAddedToStage(event:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			/*** Читаем flash-vars и инициализируем менеджер ресурсов ***/
			var fv:Object = stage.loaderInfo.parameters;
			
			RunMode.d(this);	
			Console.log("Run mode: " + RunMode.current);
			
			Security.allowDomain("*");
			AppFonts.initialize();

			addNetworkListeners();
			
			/*** Создаём прелоадер и выбираем сплеш для загрузки ***/
			if(AssetManager.getItemStatus("mc_preloader") & AssetManager.ITEM_FOUND)
			{
				_preloader = AssetManager.getMovieClip("mc_preloader");
				if(_preloader)
				{
					_preloader.x = stage.stageWidth / 2;
					_preloader.y = stage.stageHeight / 2;
					addChildAt(_preloader, 0);
					
					_progressBar = new UIProgressBar(null, _preloader["progress_bar"]);
					_progressBar.progress = 0.0;
					_progressBar.text = "0%";
				}
				AssetManager.remove("mc_preloader");
			}
			
			/*** Создаём запрос на загрузку ресурсов ***/
			for (var name:String in ASSETS)
				AssetManager.add(name, ASSETS[name]);
			
			var locale:String = "ru";
			if(fv.hasOwnProperty("locale"))
			{
				locale = fv.locale;
			}
			
			AssetManager.add("locale", "data/locale_" + locale + ".xml");
				
			if (RunMode.current == RunMode.LOCAL)
				AssetManager.add("init_farm", "data/init_farm.xml");
				
			_descriptionLoader = AssetManager.load();
			_descriptionLoader.addEventListener(Event.COMPLETE, onDescriptionLoaded);
			_descriptionLoader.load();
			
			stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function onDescriptionLoaded(event:Event):void 
		{	
			_descriptionLoaded = true;
			_descriptionLoader = null;
			
			for (var name:String in ASSETS)
			{
				AssetManager.addFromXML( AssetManager.getXML(name) );
				AssetManager.remove(name);
			}
			
			StringManager.initialize();
			StringManager.addFromXML(AssetManager.getXML("locale"));
			
			_assetLoader = AssetManager.load();
			_assetLoader.addEventListener(Event.COMPLETE, onAssetLoaded);
			_assetLoader.load();
		}
		
		private function onEnterFrame(event:Event):void 
		{
			var progress:Number = 0.0;
			
			if(_assetLoader)
				progress = _assetLoader.progress;
			
			if(_assetLoaded)
				progress = 1.0;
			
			if(_assetLoaded)
			{
				if(_networkReady)
				{
					stage.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
					start();
				}
				else
				{
					if(_someError)
					{
						if(_progressBar)
							_progressBar.text = StringManager.getText("load.error");
					}
					else
					{
						if(_progressBar)
							_progressBar.text = StringManager.getText("load.connect");
					}
				}
			}
			else
			{
				if(_progressBar)
				{
					_progressBar.progress = progress;
					_progressBar.text = int(progress*100).toString() + "%";
				}
			}
		}
		
		private function onAssetLoaded(e:Event):void
		{
			_assetLoader = null;
			_assetLoaded = true;
		}		

		private function start():void
        {
            if(_progressBar)
            {
            	_progressBar.progress = 1.0;
				_progressBar.text = StringManager.getText("load.init");
            }
            
            _main.addEventListener(Event.COMPLETE, onStartComplete);
            _main.addEventListener(ErrorEvent.ERROR, onStartError);
            _main.initialize();
		}

		private function onStartError(e:Event):void 
		{
			if(_progressBar)
			{
				_progressBar.progress = 1.0;
				_progressBar.text = StringManager.getText("load.error");
			}
		}

		private function onStartComplete(e:Event):void 
		{
			if(parent)
			{
				parent.removeChild(this);
			}
		}
	}
}
